package com.jiaok.config.securityHandler;

import cn.hutool.json.JSONUtil;
import com.jiaok.comm.CommonResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author jiaok
 * @Date 2023/5/8 18:05
 */
@Component
public class LoginFailureHandler  implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //将响应转换成流的形式
        ServletOutputStream outputStream = response.getOutputStream();

        CommonResponse result =  CommonResponse.ok("登录失败",e.getMessage());
        //将结果按照流的形式输出_且按照json格式
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UtF-8"));

        //将流输出
        outputStream.flush();
        //关闭流
        outputStream.close();
    }
}
